package com.google.code.mc4java.msg;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class TextMessage extends AbstractTextMessage {

	private byte[] msg;
	
	public static final int STRING_FLAG = 1;
	public static final int BOOLEAN_FLAG = 2;
	public static final int INT_FLAG = 3;
	public static final int LONG_FLAG = 4;
	public static final int FLOAT_FLAG = 5;
	public static final int DOUBLE_FLAG = 6;
	public static final int OBJECT_FLAG = 7;
	
	public byte[] createMessage(String key,Object value,long timeout,String cmd) {
		
		try {
			key = sanitizeKey(key);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		byte[] valBytes = encodeMsg(value);
		int flag = getFlag();
		
		String sendCmd = String.format( "%s %s %d %d %d\r\n", cmd, key, flag, 0, valBytes.length );
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			baos.write(sendCmd.getBytes());
			baos.write(valBytes);
			baos.write("\r\n".getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.msg = baos.toByteArray();
		return msg;
	}

	public byte[] createMessage(String key,String cmd) {
		try {
			key = sanitizeKey(key);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}		
		String sendCmd = String.format( "%s %s \r\n", cmd, key);
		this.msg = sendCmd.getBytes();
		return msg;
	}
	
	public byte[] getMsg() {
		return msg;
	}

	public Object parseMessage(int flag,byte[] value) {
		return decode(flag,value);
	}

}
